/**
 * Created by jige0727 on 2017/5/29.
 */
(function () {
    $(document).ready(function () {
        Messenger.options = {
            extraClasses: 'messenger-fixed messenger-on-bottom messenger-on-right',
            theme: 'flat'
        };
        utils.checkToken();
        $.ajaxSetup({
            dataType: "json",
            beforeSend: function (jqXHR, settings) {
                if (localStorage.ums_access_token) {
                    jqXHR.setRequestHeader('access_token', localStorage.ums_access_token);
                }
            },
            error: function () {
                tableHelper.showMsg('错误', 0);
                // utils.gotoLoginPage();
            }
        });
        utils.initOutFrame({sidebar_target: 'dept_list'}, function () {
            //填充事件
            drawTable();
            act_create();
            act_update();
            act_del_confirm();
            draw_tree()
        })
    })
    ///////////基本固定内容

    var listtable = {};
    var drawTable = function () {
        listtable = tableHelper.drawTable(
            '.data_tables',
            {
                colNames: [
                    '操作', '名称', '代号', '手机', '邮箱', '座机', '省份', '城市', '区县'
                ],
                dataTableCfg: { //表格的参数
                    "searching": true,
                    "processing": true,
                    "serverSide": true,
                    ordering: false,
                    select: {
                        items: 'row',
                        style: 'os',
                        selector: 'td'
                    },
                    // "dom": 'lfrtip',
                    "ajax": {
                        "url": '/ums/services/department/list',
                        "contentType": "application/json",
                        "type": "POST",
                        "data": function (d) {
                            utils.showBtnEnable(0);//把按钮装配置一下
                            var selected = $(".data_tree").jstree("get_selected");
                            if (selected && selected.length > 0) {
                                d.filterRootId = Number(selected[0]);
                            }
                            return JSON.stringify(d);
                        }
                    },
                    "columns": [{
                        orderable: false,
                        className: 'select-checkbox',
                        data: null,
                        "defaultContent": ""
                    },
                        tableHelper.genCol_name('dept_name'),
                        tableHelper.genCol_name('dept_code'),
                        tableHelper.genCol_name('mobilephone'),
                        tableHelper.genCol_name('email'),
                        tableHelper.genCol_name('tel'),
                        tableHelper.genCol_name('province'),
                        tableHelper.genCol_name('city'),
                        tableHelper.genCol_name('town'),
                    ]
                }
            }
        );

        listtable.on('select', function (e, dt, type, cell, originalEvent) {
            var count = listtable.rows({selected: true}).count();
            utils.showBtnEnable(count);
        });
        listtable.on('deselect', function (e, dt, type, cell, originalEvent) {
            var count = listtable.rows({selected: true}).count();
            utils.showBtnEnable(count);
        });
        // listtable.on('click', 'tr', function () {
        //     var data = listtable.row('.selected').data();
        //     if (data) {
        //         for (var key in data) {
        //             $(".simple_form .simple_form_data[para_name='" + key + "']").val(data[key])
        //         }
        //     } else {
        //         $(".simple_form .simple_form_data ").val('');
        //     }
        // });
    }

    var act_create = function () {
        $("#dlg_new .act_save").click(function () {
            var param = {};
            $("#dlg_new .form_data").each(function () {
                param[$(this).attr("para_name")] = $(this).val()
            });
            var selected = $(".data_tree").jstree("get_selected");
            if (selected && selected.length > 0) {
                param.parent_dept_id = Number(selected[0]);
            }
            if (utils._isNotFillTotally("#dlg_new")) {
                return;
            } else {
                utils._clearBitian("#dlg_new");
            }
            // 判断必填 完成
            console.log('param->', param);
            utils.sendPost(
                '/ums/services/department/create',
                param,
                function (res) {
                    listtable.ajax.reload();
                    tableHelper.showMsg(res.msg, res.success);
                    $(".data_tree").jstree("refresh");
                    if (res.success) {
                        $('#dlg_new').modal('hide')
                    }
                    $("#dlg_new input.form_data").val('');
                }
            );
        })
    }

    var act_update = function () {
        $('#dlg_modify').on('show.bs.modal', function (e) {
            var datas = listtable.rows({selected: true}).data();
            $.post("/ums/services/department/info", {id: datas[0].id}, function (res) {
                for (var key in res) {
                    $('#dlg_modify .form_data[para_name="' + key + '"]').val(res[key]);
                }
            })
        });
        $("#dlg_modify .act_update").click(function () {
            var param = {};
            $("#dlg_modify .form_data").each(function () {
                param[$(this).attr("para_name")] = $(this).val()
            });
            if (utils._isNotFillTotally("#dlg_modify")) {
                return;
            } else {
                utils._clearBitian("#dlg_modify");
            }
            // 判断必填 完成
            console.log('param->', param);
            utils.sendPost(
                '/ums/services/department/modify',
                param,
                function (res) {
                    listtable.ajax.reload();
                    tableHelper.showMsg(res.msg, res.success);
                    $(".data_tree").jstree("refresh");
                    if (res.success) {
                        $('#dlg_modify').modal('hide')
                    }
                    $("#dlg_modify input.form_data").val('');
                }
            );
        })
    }

    var act_del_confirm = function () {
        $(".act_del_confirm").off('click').click(function () {
            var datas = listtable.rows({selected: true}).data();
            var ids = [];
            for (var i = 0; i < datas.length; i++) {
                var item = datas[i];
                ids.push(item.id);
            }
            utils.sendPost(
                '/ums/services/department/delete',
                ids,
                function (res) {
                    listtable.ajax.reload();
                    tableHelper.showMsg(res.msg, res.success);
                    $(".data_tree").jstree("refresh");
                }
            );
        })
    }

    var draw_tree = function () {
        $('.data_tree')
        // .on("ready.jstree", function (e, data) {
        //     $(".data_tree").jstree("open_all");
        // })
            .on("select_node.jstree", function (e, data) {
                listtable.ajax.reload();
            })
            .jstree({
                'core': {
                    "multiple": false,
                    'data': function (obj, cb) {
                        $.post("/ums/services/department/list-tree", function (data) {
                            for (var i = 0; i < data.length; i++) {
                                data[i]["state"] = {opened: true};
                            }
                            cb.call(this, data);
                        })

                    }
                },
                // "checkbox": {
                //     "keep_selected_style": false,
                //     three_state: false,
                // },
                // "plugins": ["sort"],
                // 'sort': function (a, b) {
                //     return this.get_node(a).original.sort_order > this.get_node(b).original.sort_order ? 1 : -1;
                // }
            });
    }
})();